<template>
  <div class="page-container">
    <h2>环境监测中心</h2>

    <!-- 环境监测数据录入表单 -->
    <el-card header="环境监测数据录入" class="form-card">
      <DynamicForm
        :config="formConfig"
        v-model="formData"
        :loading="loading"
        @submit="handleSubmit"
        @reset="handleReset"
      />
    </el-card>

    <!-- 监测数据显示 -->
    <el-card header="实时监测数据" class="data-card">
      <DataTable 
        :config="tableConfig" 
        :data="monitoringData"
        :total="monitoringData.length"
        :current-page="currentPage"
        :page-size="pageSize"
        @search="handleTableSearch"
        @filter="handleTableFilter"
        @page-change="handlePageChange"
        @action="handleTableAction"
      >
        <template #operation="{ row }">
          <el-button size="small" @click="handleViewDetail(row)">查看详情</el-button>
          <el-button size="small" type="danger" @click="handleDeleteRecord(row)">删除</el-button>
        </template>
      </DataTable>
    </el-card>
  </div>
</template>

<script setup lang="ts">
  import { ref, reactive } from 'vue'
  import DynamicForm from '@/components/DynamicForm.vue'
  import DataTable from '@/components/DataTable.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'

  const loading = ref(false)
  const formData = reactive({})
  const currentPage = ref(1)
  const pageSize = ref(10)

  // 表单配置
  const formConfig = {
    labelWidth: '120px',
    fields: [
      {
        prop: 'airQuality',
        label: '空气质量指数',
        type: 'input',
        inputType: 'number',
        required: true,
        placeholder: '请输入空气质量指数',
        prefixIcon: 'el-icon-wind-power'
      },
      {
        prop: 'noiseLevel',
        label: '噪音分贝',
        type: 'input',
        inputType: 'number',
        required: true,
        placeholder: '请输入噪音分贝值',
        prefixIcon: 'el-icon-microphone'
      },
      {
        prop: 'temperature',
        label: '温度(°C)',
        type: 'input',
        inputType: 'number',
        required: true,
        placeholder: '请输入温度值',
        prefixIcon: 'el-icon-sunny'
      },
      {
        prop: 'humidity',
        label: '湿度(%)',
        type: 'input',
        inputType: 'number',
        required: true,
        placeholder: '请输入湿度值',
        prefixIcon: 'el-icon-cloudy'
      },
      {
        prop: 'pm25',
        label: 'PM2.5',
        type: 'input',
        inputType: 'number',
        required: true,
        placeholder: '请输入PM2.5值',
        prefixIcon: 'el-icon-fog'
      },
      {
        prop: 'location',
        label: '监测位置',
        type: 'select',
        required: true,
        placeholder: '请选择监测位置',
        options: [
          { label: '市中心', value: 'city_center' },
          { label: '工业区', value: 'industrial_area' },
          { label: '居民区', value: 'residential_area' },
          { label: '公园', value: 'park' }
        ]
      },
      {
        prop: 'status',
        label: '监测状态',
        type: 'radio',
        required: true,
        options: [
          { label: '正常', value: 'normal' },
          { label: '预警', value: 'warning' },
          { label: '异常', value: 'abnormal' }
        ]
      },
      {
        prop: 'remarks',
        label: '备注',
        type: 'textarea',
        placeholder: '请输入备注信息',
        rows: 3
      }
    ],
    submitText: '提交监测数据',
    resetText: '重置表单'
  }

  // 表格配置
  const tableConfig = {
    columns: [
      {
        prop: 'time',
        label: '时间',
        width: 180,
        filterable: true,
        filterOptions: [
          { label: '今天', value: 'today' },
          { label: '昨天', value: 'yesterday' }
        ]
      },
      {
        prop: 'airQuality',
        label: '空气质量指数',
        width: 120,
        sortable: true,
        filterable: true,
        filterOptions: [
          { label: '优 (0-50)', value: 'excellent' },
          { label: '良 (51-100)', value: 'good' },
          { label: '轻度污染 (101-150)', value: 'light' },
          { label: '中度污染 (151-200)', value: 'moderate' }
        ]
      },
      {
        prop: 'noiseLevel',
        label: '噪音分贝',
        width: 100,
        sortable: true
      },
      {
        prop: 'temperature',
        label: '温度(°C)',
        width: 100,
        sortable: true
      },
      {
        prop: 'humidity',
        label: '湿度(%)',
        width: 100,
        sortable: true
      },
      {
        prop: 'pm25',
        label: 'PM2.5',
        width: 100,
        sortable: true
      },
      {
        prop: 'status',
        label: '状态',
        width: 100,
        filterable: true,
        filterOptions: [
          { label: '正常', value: '正常' },
          { label: '预警', value: '预警' },
          { label: '异常', value: '异常' }
        ]
      }
    ],
    filters: [
      {
        prop: 'status',
        label: '状态筛选',
        options: [
          { label: '全部', value: '' },
          { label: '正常', value: '正常' },
          { label: '预警', value: '预警' },
          { label: '异常', value: '异常' }
        ]
      }
    ],
    actions: [
      {
        name: 'export',
        label: '导出数据',
        type: 'success',
        icon: 'Download'
      },
      {
        name: 'refresh',
        label: '刷新数据',
        type: 'primary',
        icon: 'Refresh'
      }
    ],
    showToolbar: true,
    showSearch: true,
    searchPlaceholder: '搜索监测数据...',
    showSelection: true,
    showIndex: true,
    operationColumn: true,
    operationLabel: '操作',
    showPagination: true,
    border: true,
    stripe: true,
    size: 'default',
    rowKey: 'time'
  }

  // 模拟监测数据
  const monitoringData = ref([
    {
      time: '2024-01-15 10:30:00',
      airQuality: 45,
      noiseLevel: 65,
      temperature: 25,
      humidity: 60,
      pm25: 35,
      status: '正常'
    },
    {
      time: '2024-01-15 09:15:00',
      airQuality: 68,
      noiseLevel: 72,
      temperature: 26,
      humidity: 58,
      pm25: 42,
      status: '预警'
    },
    {
      time: '2024-01-15 08:00:00',
      airQuality: 85,
      noiseLevel: 78,
      temperature: 24,
      humidity: 65,
      pm25: 55,
      status: '异常'
    }
  ])

  // 处理表单提交
  const handleSubmit = async (data: any) => {
    loading.value = true

    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000))

      // 添加新数据到表格
      const newRecord = {
        time: new Date().toLocaleString('zh-CN'),
        ...data,
        status: getStatusLabel(data.status)
      }

      monitoringData.value.unshift(newRecord)

      ElMessage.success('监测数据提交成功！')

      // 清空表单
      Object.keys(formData).forEach(key => {
        formData[key] = ''
      })
    } catch (error) {
      ElMessage.error('提交失败，请重试')
    } finally {
      loading.value = false
    }
  }

  // 处理表单重置
  const handleReset = () => {
    ElMessage.info('表单已重置')
  }

  // 获取状态标签
  const getStatusLabel = (statusValue: string) => {
    const statusMap: Record<string, string> = {
      normal: '正常',
      warning: '预警',
      abnormal: '异常'
    }
    return statusMap[statusValue] || statusValue
  }

  // 获取状态类型用于标签颜色
  const getStatusType = (status: string) => {
    const typeMap: Record<string, string> = {
      正常: 'success',
      预警: 'warning',
      异常: 'danger'
    }
    return typeMap[status] || 'info'
  }

  // 表格搜索处理
  const handleTableSearch = (searchText: string) => {
    console.log('搜索内容:', searchText)
    ElMessage.info(`搜索关键词: ${searchText}`)
  }

  // 表格筛选处理
  const handleTableFilter = (filters: Record<string, any>) => {
    console.log('筛选条件:', filters)
    ElMessage.info('筛选条件已应用')
  }

  // 分页处理
  const handlePageChange = (pagination: { currentPage: number; pageSize: number }) => {
    console.log('分页变化:', pagination)
    currentPage.value = pagination.currentPage
    pageSize.value = pagination.pageSize
  }

  // 表格操作处理
  const handleTableAction = (action: any) => {
    switch (action.name) {
      case 'export':
        ElMessage.success('数据导出成功')
        break
      case 'refresh':
        ElMessage.info('数据已刷新')
        break
      default:
        console.log('未知操作:', action)
    }
  }

  // 查看详情
  const handleViewDetail = (row: any) => {
    ElMessageBox.alert(`
      <div>
        <p><strong>时间:</strong> ${row.time}</p>
        <p><strong>空气质量:</strong> ${row.airQuality}</p>
        <p><strong>噪音:</strong> ${row.noiseLevel} dB</p>
        <p><strong>温度:</strong> ${row.temperature}°C</p>
        <p><strong>湿度:</strong> ${row.humidity}%</p>
        <p><strong>PM2.5:</strong> ${row.pm25}</p>
        <p><strong>状态:</strong> ${row.status}</p>
      </div>
    `, '监测数据详情', {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭'
    })
  }

  // 删除记录
  const handleDeleteRecord = (row: any) => {
    ElMessageBox.confirm(
      `确定要删除 ${row.time} 的监测记录吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    ).then(() => {
      const index = monitoringData.value.findIndex(item => item.time === row.time)
      if (index > -1) {
        monitoringData.value.splice(index, 1)
        ElMessage.success('删除成功')
      }
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }
</script>

<style scoped>
  .page-container {
    padding: 20px;
  }

  .form-card {
    margin-bottom: 20px;
  }

  .data-card {
    margin-top: 20px;
  }
</style>
